import path from 'path';
import express, { Express, Request, Response, NextFunction } from 'express';
import chalk from 'chalk';
import morgan from 'morgan';
import cors from 'cors';
import helmet from 'helmet'
import HttpCodes from 'http-status-codes'

import logRequest from "./middleware/logRequest"
import errorMiddleware from "./middleware/errorMiddleware";

import config from './config'
import dbHelper from "./utils/dbHelper";
import HttpException from './models/httpException';

import * as userController from './controller/user';
import * as sliderController from './controller/slider';
import * as dogController from './controller/dog';
import multer from 'multer';

const app: Express = express();
const storage= multer.diskStorage({
    destination:path.resolve(__dirname,"../../client/dist/images","uploads"),
    filename: function (req, file, cb) {
        console.info(file.originalname);
        let singfileArray = file.originalname.split('.');
        let fileExtension = singfileArray[singfileArray.length - 1];    
        cb(null, singfileArray[0] + '-' + Date.now() + "." + fileExtension);
      }
})
const upload=multer({storage})

// 中间件
app.use(morgan("dev"));//日志中间件
app.use(cors());//跨域中间件
app.use(helmet());//防止xss攻击中间件
app.use(express.static(path.resolve(__dirname, "public")));//静态资源中间件
app.use(logRequest());//原生http request请求调试中间件
app.use(express.json());//请求头 Content-Type=application/json,json数据解析到req.body上
app.use(express.raw()); //"application/octet-stream"
app.use(express.text());// "application/json"
app.use(express.urlencoded({ extended: false }));////请求头 content-type:"application/x-www-form-urlencoded",表单数据解析到req.body上

app.get("/", function (req: Request, res: Response) {
    // res.statusCode=404;
    res.json({ message: "hello jaasdsa" })
})

app.post("/api/user/register",userController.register);
app.post("/api/user/login",userController.login);
app.get("/api/user/validate",userController.validate);
app.post("/api/user/uploadAvatar",upload.single("avatar"),userController.uploadAvatar);
app.get("/api/slider/list",sliderController.list);
app.get("/api/dog/list",dogController.list);
app.get("/api/dog/:id",dogController.get);

// 走到下面就没有业务逻辑了直接给404

app.use((req: Request, res: Response, next: NextFunction) => {
    next(new HttpException(HttpCodes.NOT_FOUND, "route not fund"))
})
app.use(errorMiddleware);//最后-错误处理中间件

(async () => {
    try{
        await dbHelper.initialDB();
        app.listen(config.PORT, () => {
            console.log(chalk.green(`服务已在端口:【${config.PORT}】启动`))
        })
    }
    catch (e) {
        console.log(chalk.red(e));
    }
})()

console.log("main");


